<?php


namespace Xtsb\Cims\Ocr\Custom;


use Xtsb\Cims\File\File;
use Xtsb\Cims\Ocr\Invoice\BaseOcr;
use app\Http\Finance\Servers\FinanceCostInvoiceServer;
use app\Http\Finance\Servers\FinanceInvoicePageServer;
use think\facade\Db;

class Custom extends BaseOcr
{
  static function run(){
    $invoice_class = input('invoice_class');
    $type = input('type');
    $goods_supplier_id = input('goods_supplier_id');
    $multi_supplier = (bool)input('multi_supplier');

    $dirname = self::getDirname($type);
    $files = File::getFile($dirname, null, null, "请先点击按钮：1.附件上传，将您需要识别的票据上传");

    $remain_error = "";
    self::$file_num = count($files);
    foreach ($files as $file) {
      $remain_error = FinanceInvoicePageServer::checkOcrNumber();
      if(!empty($remain_error)){
        break;
      }
      $file_name = str_replace('|', '', $file);
      $url = self::getImageUrlByRemote($dirname,$file_name,3.9);
      $data = self::request($url);
      if($data){
        Db::starttrans();
        if(!$multi_supplier && $goods_supplier_id){
          $data['goods_supplier_id'] = $goods_supplier_id;
        }
        FinanceInvoicePageServer::insert($data, $invoice_class, $type, $dirname, $file_name);
        Db::commit();
        self::$point_suc++;
      }else{
        self::$point_err++;
      }
    }
    return self::ocrMessage($remain_error);
  }

  //前端页面参数配置
  static function config($data){
    $type = $data['type'];
    return [
      'dirname'=>self::getDirname($type),
      'apply_title'=>$type?FinanceCostInvoiceServer::TYPE_LIST[$type]['apply_title']:'',
      'label'=>'其他票据上传识别',
      'ocr_btn'=>[
        [
          'title'=>'2.识别票据',
          'type'=>'create',
          'data_url'=>'FinanceInvoicePage/invoiceCustomOcr/Finance',
        ]
      ],
      'invoice_class'=>$data['invoice_class'],
      'table_name'=>$type,
      'upload_btn'=>[
        [
          'title'=>'1.附件上传',
          'type'=>'create',
          'api'=>''
        ]
      ],
      'visible'=>false,
      'desc'=>"<span class='text-yellow'>【发票附件识别说明】 </span>
<br>1. 支持文件格式:".implode('/',  ['jpeg','jpg','png','bmp'])."
<br>2. 每个附件对应<span class='text-red'>一张</span>票据(否则会识别失败)
<br>3. <span class='text-red'>仅支持识别</span>火车票/卷票/机票
<br>4. 上传完毕后，请关闭本页面，点击按钮： 识别发票，系统自动开始识别上传的发票附件
",
      'foot_btn'=>[
        ['type'=>'CLOSE', 'name'=>'关闭']
      ],
      'ocr_message_label'=>'发票识别结果',
      'foot_btn_my_invoice'=>[
        ['type'=>'CLOSE', 'name'=>'保存']
      ],
      'visible_my_invoice'=>false,
      'my_invoice_upload_title'=>'票据附件上传',
      'my_invoice_title'=>'我的新增票据',
    ];
  }

  //请求结果解析
  static function request($host){
    $json = self::api($host);

    $data = $json['subMsgs']??[];
    $body = $data[0]??[];
    $type = $body["type"]??"";
    $result = $body['result']??[];
    $data = $result['data']??[];
    if($type == '卷票' && $data){
      return Invoice::struct($data);
    }elseif ($type == '火车票' && $data){
      return Train::structure($data);
    }
    return [];
  }

  //阿里云请求
  static function api($img_url){
    $host = "https://multcommon.market.alicloudapi.com";
    $path = "/ocrservice/mixedMultiCommon";
    $method = "POST";
    $appcode = "44a54701b3254629a4ab4a0daac7e680";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    //根据API的要求，定义相对应的Content-Type
    array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
    $querys = "";
    $bodys = json_encode(['url'=>$img_url,'img'=>'']);
    $url = $host . $path;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    if (1 == strpos("$".$host, "https://"))
    {
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
    $result = curl_exec($curl);
    return json_decode($result,true);
  }

  static function getDirname($type){
    return get_dirname('invoice_ocr_custom/'.SID.'/'.$type);
  }
}